package Frames;

import DAO.Dao;
import Entidades.Receptor;
import Entidades.Saida;
import Entidades.TipoSaida;
import Entidades.Usuario;
import Utils.FixedLengthDocument;
import Utils.S20BinaryLookup;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Davidson
 */
public class IfrmLancarSaida extends javax.swing.JInternalFrame {

    Dao dao = new Dao();
    List<TipoSaida> tipoSaida = dao.listarTipoSaida();
    List<Receptor> receptores = dao.listarReceptores();
    Usuario usuario;    
        
    public IfrmLancarSaida(Usuario usuario){
        initComponents();
        this.usuario = usuario;
        ftfDataInicial.setText(new SimpleDateFormat("dd/MM/yyyy").format(new Date()));
        lbUsuario.setText(usuario.getNome());
        try {
            carregaTiposSaidas();
            carregaReceptores();
        } catch (SQLException ex) {
            Logger.getLogger(IfrmLancarSaida.class.getName()).log(Level.SEVERE, null, ex);
        }        
        new S20BinaryLookup(cbReceptores);        
    }    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgSituacao = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        ftfDataInicial = new javax.swing.JFormattedTextField();
        imgDataInicial = new javax.swing.JLabel();
        cbReceptores = new javax.swing.JComboBox();
        cbTipoSaida = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        ftfValorSaida = new javax.swing.JFormattedTextField();
        jLabel6 = new javax.swing.JLabel();
        btGravarSaida = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescricao = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        txtUsuario = new javax.swing.JLabel();
        lbUsuario = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbSaidas = new javax.swing.JTable();

        setClosable(true);
        setFrameIcon(null);
        setMinimumSize(new java.awt.Dimension(758, 361));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lançamento de Saídas"));

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 51));
        jLabel1.setText("Data da saída:");

        ftfDataInicial.setForeground(new java.awt.Color(102, 102, 102));
        ftfDataInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        ftfDataInicial.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        ftfDataInicial.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        ftfDataInicial.setMaximumSize(new java.awt.Dimension(126, 30));
        ftfDataInicial.setMinimumSize(new java.awt.Dimension(126, 30));
        ftfDataInicial.setPreferredSize(new java.awt.Dimension(126, 30));

        imgDataInicial.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/calendar.png"))); // NOI18N
        imgDataInicial.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        imgDataInicial.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                imgDataInicialMouseClicked(evt);
            }
        });

        cbReceptores.setEditable(true);
        cbReceptores.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        cbReceptores.setForeground(new java.awt.Color(41, 41, 41));
        cbReceptores.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione" }));
        cbReceptores.setMaximumSize(new java.awt.Dimension(250, 30));
        cbReceptores.setMinimumSize(new java.awt.Dimension(250, 30));
        cbReceptores.setPreferredSize(new java.awt.Dimension(250, 30));
        cbReceptores.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbReceptoresItemStateChanged(evt);
            }
        });

        cbTipoSaida.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        cbTipoSaida.setForeground(new java.awt.Color(41, 41, 41));
        cbTipoSaida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione" }));
        cbTipoSaida.setMaximumSize(new java.awt.Dimension(180, 30));
        cbTipoSaida.setMinimumSize(new java.awt.Dimension(180, 30));
        cbTipoSaida.setPreferredSize(new java.awt.Dimension(180, 30));

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setText("Tipo Saída:");

        jLabel5.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 51, 51));
        jLabel5.setText("Receptor:");

        ftfValorSaida.setDocument(new FixedLengthDocument(10));
        ftfValorSaida.setForeground(new java.awt.Color(102, 102, 102));
        ftfValorSaida.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###0.00"))));
        ftfValorSaida.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        ftfValorSaida.setText("0,00");
        ftfValorSaida.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N
        ftfValorSaida.setMaximumSize(new java.awt.Dimension(100, 30));
        ftfValorSaida.setMinimumSize(new java.awt.Dimension(100, 30));
        ftfValorSaida.setPreferredSize(new java.awt.Dimension(100, 30));
        ftfValorSaida.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ftfValorSaidaFocusGained(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(51, 51, 51));
        jLabel6.setText("Valor:");

        btGravarSaida.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        btGravarSaida.setText("Gravar");
        btGravarSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGravarSaidaActionPerformed(evt);
            }
        });

        txtDescricao.setColumns(10);
        txtDescricao.setRows(5);
        txtDescricao.setBorder(null);
        jScrollPane2.setViewportView(txtDescricao);

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(41, 41, 41));
        jLabel2.setText("Descrição:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane2))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbTipoSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbReceptores, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(ftfValorSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(ftfDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(imgDataInicial)
                        .addGap(18, 18, 18)
                        .addComponent(btGravarSaida))
                    .addComponent(jLabel1))
                .addGap(74, 74, 74))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel1)
                    .addComponent(jLabel6))
                .addGap(0, 0, 0)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbReceptores, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(ftfValorSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(ftfDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cbTipoSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(imgDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btGravarSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(0, 0, 0)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        txtUsuario.setText("Usuário:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtUsuario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbUsuario)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsuario)
                    .addComponent(lbUsuario))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        tbSaidas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tipo Saída", "Receptor", "Valor", "Data saída"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbSaidas.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tbSaidas);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void imgDataInicialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imgDataInicialMouseClicked
        frmCalendar dialog = new frmCalendar(new javax.swing.JFrame(), false, ftfDataInicial);
        int x = getBounds().x;
        int y = getBounds().y;
        dialog.setBounds(x + 500, y + 193, 224, 140);
        dialog.setVisible(true);
    }//GEN-LAST:event_imgDataInicialMouseClicked

    private void ftfValorSaidaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftfValorSaidaFocusGained
        ftfValorSaida.selectAll();
    }//GEN-LAST:event_ftfValorSaidaFocusGained

    private void btGravarSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGravarSaidaActionPerformed
        if("Selecione".equals(cbTipoSaida.getSelectedItem())){
            JOptionPane.showMessageDialog(rootPane, "Selecione o tipo de Saída!");
            cbTipoSaida.requestFocus();
            return;
        }
        if("Selecione".equals(cbReceptores.getSelectedItem())){
            JOptionPane.showMessageDialog(rootPane, "Selecione o Receptor");
            cbReceptores.requestFocus();
            return;
        }
        if(ftfValorSaida.getText().equals("0,00")){
            JOptionPane.showMessageDialog(rootPane, "Digite o valor!");
            ftfValorSaida.requestFocus();
            return;
        }        
        Saida saida = new Saida();
        saida.setIdUsuario(usuario.getId());        
        try {
            saida.setDtReferencia(new SimpleDateFormat("dd/MM/yyyy").parse(ftfDataInicial.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(IfrmLancarSaida.class.getName()).log(Level.SEVERE, null, ex);
        }
        Iterator<Receptor> it = receptores.iterator();
        while(it.hasNext()){
            Receptor r = it.next();
            String nome = r.getNome();
            int id = r.getId();
            if (nome.equals(cbReceptores.getSelectedItem())) {
                saida.setIdReceptor(id);
            }
        }
        Iterator<TipoSaida> it2 = tipoSaida.iterator();
        while (it2.hasNext()) {
            TipoSaida ts = it2.next();
            String nome = ts.getNome();            
            int id = ts.getId();
            if (nome.equals(cbTipoSaida.getSelectedItem())) {
                saida.setIdTipo(id);
            }
        }
        saida.setValor(Double.valueOf(ftfValorSaida.getText().replaceAll(",", ".")));
        saida.setDescricao(txtDescricao.getText());
        Saida retornoSaida = new Saida();
        try {
            retornoSaida = dao.lancarSaida(saida);
        } catch (SQLException ex) {
            Logger.getLogger(IfrmLancarSaida.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(IfrmLancarSaida.class.getName()).log(Level.SEVERE, null, ex);
        }
        //System.out.println(retornoEntrada.getNomeTipoEntrada()+" - "+retornoEntrada.getNomeEmissor()+" - "+retornoEntrada.getValor()+" - "+new SimpleDateFormat("dd/MM/yyyy").format(retornoEntrada.getDtReferencia()));
        
        DefaultTableModel model = (DefaultTableModel) tbSaidas.getModel();
        String nomeTipoSaida = retornoSaida.getNomeTipoSaida();
        String nomeEmissor = retornoSaida.getNomeReceptor();
        String valor = String.valueOf(new DecimalFormat("#,###.00").format(retornoSaida.getValor()));
        String dtReferencia = new SimpleDateFormat("dd/MM/yyyy").format(retornoSaida.getDtReferencia());
        
        Object[] dados = {nomeTipoSaida,nomeEmissor,valor,dtReferencia};
        model.addRow(dados);
        limpaCampos();
    }//GEN-LAST:event_btGravarSaidaActionPerformed

    private void cbReceptoresItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbReceptoresItemStateChanged
        Iterator<Receptor> it = receptores.iterator();
        while(it.hasNext()){
            Receptor r = it.next();
            String nome = r.getNome();
            int id = r.getId();
            if (nome.equals(cbReceptores.getSelectedItem())) {
                System.out.println("Id: "+id+" Nome: "+nome);
            }
        }
    }//GEN-LAST:event_cbReceptoresItemStateChanged

    private void carregaTiposSaidas() throws SQLException{
        Iterator<TipoSaida> it = tipoSaida.iterator();
        while(it.hasNext()){
            cbTipoSaida.addItem(it.next().getNome());
        }        
    }
    private void carregaReceptores() throws SQLException{
        Iterator<Receptor> it = receptores.iterator();
        while(it.hasNext()){
            cbReceptores.addItem(it.next().getNome());
        }
    }
    
    private void limpaCampos(){
        cbTipoSaida.setSelectedIndex(0);
        cbReceptores.setSelectedIndex(0);
        ftfValorSaida.setText("0,00");
        ftfDataInicial.setText(new SimpleDateFormat("dd/MM/yyyy").format(new Date()));
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgSituacao;
    private javax.swing.JButton btGravarSaida;
    private javax.swing.JComboBox cbReceptores;
    private javax.swing.JComboBox cbTipoSaida;
    private javax.swing.JFormattedTextField ftfDataInicial;
    private javax.swing.JFormattedTextField ftfValorSaida;
    private javax.swing.JLabel imgDataInicial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbUsuario;
    private javax.swing.JTable tbSaidas;
    private javax.swing.JTextArea txtDescricao;
    private javax.swing.JLabel txtUsuario;
    // End of variables declaration//GEN-END:variables
}
